package com.twu.biblioteca.model;

import com.google.inject.Inject;

import com.twu.biblioteca.dao.BookDao;
import com.twu.biblioteca.entity.Book;
import com.twu.biblioteca.exception.CheckoutFailException;
import com.twu.biblioteca.exception.ReturnFailException;

import java.util.List;

public class BookModel {
  private final BookDao dao;

  @Inject
  public BookModel(BookDao dao) {
    this.dao = dao;
  }

  public List<Book> checkout(Book book) {
    List<Book> allAvailableBooks = dao.getAvailableBooks();
    if (!allAvailableBooks.contains(book)) {
      throw new CheckoutFailException("Book is not "
          + "existing or already checked out");
    }

    for (Book b : allAvailableBooks) {
      if (b.getIsbn() == book.getIsbn()) {
        b.setAvailable(false);
        dao.update(b.getUuid(), b);
        break;
      }
    }

    return dao.getAvailableBooks();
  }

  public List<Book> returnBook(Book book) {
    List<Book> allNotAvailableBooks = dao.getCheckoutBooks();
    if (!allNotAvailableBooks.contains(book)) {
      throw new ReturnFailException("Request is not valid, check book again");
    }

    for (Book b : allNotAvailableBooks) {
      if (b.getIsbn() == book.getIsbn()) {
        b.setAvailable(true);
        dao.update(b.getUuid(), b);
        break;
      }
    }

    return dao.getAvailableBooks();
  }

  public List<Book> getAvailableBooks() {
    return dao.getAvailableBooks();
  }

  public List<Book> getCheckoutBook() {
    return dao.getCheckoutBooks();
  }
}
